package com.wing.system.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.system.dao.DingTalkAttendanceGroupDao;
import com.wing.system.dao.DingTalkAttendanceGroupSettingDao;
import com.wing.system.dao.DingTalkAttendanceGroupSettingTimesDao;
import com.wing.system.model.entity.DingTalkAttendanceGroup;
import com.wing.system.model.entity.DingTalkAttendanceGroupSetting;
import com.wing.system.model.entity.DingTalkAttendanceGroupSettingTimes;
import com.wing.system.model.response.DingTalkAttendanceGroupVo;
import com.wing.system.model.response.DingTalkAttendanceVO;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.SystemDingTalkInfo;
import com.wing.user.model.request.User;
import com.wing.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 考勤组service
 * @author
 */
@Service
@Slf4j
public class DingTalkAttendanceGroupServiceImpl extends ServiceImpl<DingTalkAttendanceGroupDao, DingTalkAttendanceGroup> implements DingTalkAttendanceGroupService {

    @Autowired
    UserClient userClient;

    @Autowired
    DingTalkAttendanceGroupSettingDao dingTalkAttendanceGroupSettingDao;

    @Autowired
    DingTalkAttendanceGroupSettingTimesDao dingTalkAttendanceGroupSettingTimesDao;

    @Override
    public void syncDingAttendanceGroupToSystem() throws Exception {
        //获取钉钉后台配置相关
        SystemDingTalkInfo systemDingTalkInfo = userClient.getUserDingConfigInfo();
        if(systemDingTalkInfo!=null) {
            //获取钉钉后台accessToken
            String accessToken = DingDingUtils.getAccessTokenByKeySecret(systemDingTalkInfo.getClientId(), systemDingTalkInfo.getClientSecret());
            String getSimpleGroupsDetail = DingDingUtils.getsimplegroupsDetail(accessToken);
            JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(getSimpleGroupsDetail);
            if(jsonObject.containsKey("result")){
                JSONObject result = jsonObject.getJSONObject("result");
                if(result.containsKey("groups")){
                    JSONArray groupsArray = result.getJSONArray("groups");
                    for (int i = 0; i < groupsArray.size(); i++) {
                        JSONObject group = groupsArray.getJSONObject(i);
                        DingTalkAttendanceGroup dingTalkAttendanceGroup = new DingTalkAttendanceGroup();
                        if(group.containsKey("group_id")){
                            dingTalkAttendanceGroup.setGroupId(group.getLong("group_id"));
                        }
                        if(group.containsKey("group_name")){
                            dingTalkAttendanceGroup.setGroupName(group.getString("group_name"));
                        }
                        if(group.containsKey("is_default")){
                            dingTalkAttendanceGroup.setIsDefault(group.getString("is_default"));
                        }
                        if(group.containsKey("type")){
                            dingTalkAttendanceGroup.setType(group.getString("type"));
                        }
                      /*  if(group.containsKey("type")){
                            dingTalkAttendanceGroup.setType(group.getString("type"));
                        }*/
                        if(group.containsKey("member_count")){
                            dingTalkAttendanceGroup.setMemberCount(Long.valueOf(group.getString("member_count")));
                        }
                        if(group.containsKey("default_class_id")){
                            dingTalkAttendanceGroup.setDefaultClassId(Long.valueOf(group.getString("default_class_id")));
                        }
                        if(group.containsKey("work_day_list")){
                            dingTalkAttendanceGroup.setWorkDayList(group.getJSONArray("work_day_list").toString());
                        }
                        if(group.containsKey("classes_list")){
                            dingTalkAttendanceGroup.setClassesList(group.getJSONArray("classes_list").toString());
                        }
                        if(group.containsKey("manager_list")){
                            dingTalkAttendanceGroup.setManagerList(group.getJSONArray("manager_list").toString());
                        }
                        if(group.containsKey("dept_name_list")){
                            dingTalkAttendanceGroup.setDeptNameList(group.getJSONArray("dept_name_list").toString());
                        }
                        if(group.containsKey("owner_user_id")){
                            dingTalkAttendanceGroup.setOwnerUserId(group.getString("owner_user_id"));
                        }
                        if(group.containsKey("selected_class")){
                            dingTalkAttendanceGroup.setSelectedClass(group.getJSONArray("selected_class").toString());
                        }
                        dingTalkAttendanceGroup.setSource(1);
                        DingTalkAttendanceGroup talkAttendanceGroup = baseMapper.selGroupInfo(dingTalkAttendanceGroup.getGroupId());
                        if(talkAttendanceGroup!=null){
                            //更新数据
                            dingTalkAttendanceGroup.setId(talkAttendanceGroup.getId());
                            baseMapper.updateById(dingTalkAttendanceGroup);
                        }else{
                            baseMapper.insert(dingTalkAttendanceGroup);
                        }


                        //同步考勤组系统 设置的相关时间 入系统
                        syncDingAttendanceGroupSettingToSystem(group,dingTalkAttendanceGroup.getId());


                    }
                }

            }

        }

    }

    @Override
    public Page<DingTalkAttendanceGroupVo> selDingTalkAttendanceGroupInfo(Page<DingTalkAttendanceGroupVo> pg, Map map) {
        List<DingTalkAttendanceGroupVo> vos = baseMapper.selDingTalkAttendanceGroupInfo(pg, map);
        for (DingTalkAttendanceGroupVo vo : vos) {
            if(StringUtils.isNotEmpty(vo.getDeptNameList())){
                String deptNameList = toStringBufferDept(vo.getDeptNameList());
                vo.setDeptNameList(deptNameList);
            }

            String ownerUserId = vo.getOwnerUserId();


            List<User> userList= userClient.selUserDingInfo();
            Optional<User> matchedUser = userList.stream()
                    .filter(user -> ownerUserId.equals(user.getDingUserId()))
                    .findFirst();

            String userName = matchedUser.map(User::getNickname).orElse(null);
            vo.setOwnerUserName(userName);


            //   `type` varchar(255) DEFAULT NULL COMMENT '考勤类型。\r\n\r\nFIXED为固定排班\r\n\r\nTURN为轮班排班\r\n\r\nNONE为无班次',
            String type = vo.getType();
            if(type.equals("FIXED")){
                vo.setTypeName("固定排班");
            }else if(type.equals("TURN")){
                vo.setTypeName("轮班排班");
            }else if(type.equals("NONE")){
                vo.setTypeName("无班次");
            }

            vo.setClassSize(toGetBanCiSize(vo.getClassesList()));


        }
        pg.setRecords(vos);
        return pg;
    }

    public String toStringBufferDept(String deptNameList){
        // 解析整个JSON字符串
     /*   JSONObject jsonObject = JSON.parseObject(deptNameList);

        // 获取deptNameList字段的值，并去除首尾的引号
        String deptNameListStr = jsonObject.getString("deptNameList").replaceAll("^\"|\"$", "");
*/
        // 将字符串形式的数组转换为JSONArray
        JSONArray deptNameArray = JSON.parseArray(deptNameList);

        // 构建逗号分隔的字符串
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < deptNameArray.size(); i++) {
            sb.append(deptNameArray.getString(i));
            if (i < deptNameArray.size() - 1) {
                sb.append(", ");
            }
        }
        return sb.toString();

    }


    public int toGetBanCiSize(String classesList){
        // 解析整个JSON字符串

        // 将字符串形式的数组转换为JSONArray
        JSONArray classesArray = JSON.parseArray(classesList);

        return classesArray.size();

    }




    /**
     * 同步考勤组系统 设置的相关时间 入系统
     * @throws Exception
     */
    public void syncDingAttendanceGroupSettingToSystem(JSONObject groupObject,Long id) throws Exception {
        try {
            // 检查是否存在selected_class键，并获取其值
            if (groupObject.containsKey("selected_class")) {
                JSONArray selectedClassArray = groupObject.getJSONArray("selected_class");
                //删除对应历史排班时间
                if(selectedClassArray.size()>0){
                    dingTalkAttendanceGroupSettingTimesDao.delGroupSettingTimes(id);
                }

                // 遍历selected_class数组中的每个元素
                for (int j = 0; j < selectedClassArray.size(); j++) {
                    JSONObject selectedClassObject = selectedClassArray.getJSONObject(j);
                    Long groupId = groupObject.getLong("group_id");
                    String groupName = groupObject.getString("group_name");

                    // 提取并打印selected_class中的信息
                    Long classId = selectedClassObject.getLong("class_id");
                    String className = selectedClassObject.getString("class_name");

                    // 如果需要处理setting部分，可以类似地进行
                    JSONObject settingObject = selectedClassObject.getJSONObject("setting");
                    Integer absenteeismLateMinutes = settingObject.getInteger("absenteeism_late_minutes");
                    Long classSettingId = settingObject.getLong("class_setting_id");
                    String isOffDutyFreeCheck = settingObject.getString("is_off_duty_free_check");
                    Integer permitLateMinutes = settingObject.getInteger("permit_late_minutes");
                    Integer seriousLateMinutes = settingObject.getInteger("serious_late_minutes");
                    Integer workTimeMinutes = settingObject.getInteger("work_time_minutes");
                    DingTalkAttendanceGroupSetting dingTalkAttendanceGroupSetting=new DingTalkAttendanceGroupSetting();

                    dingTalkAttendanceGroupSetting.setWorkTimeMinutes(workTimeMinutes);
                    dingTalkAttendanceGroupSetting.setSeriousLateMinutes(seriousLateMinutes);
                    dingTalkAttendanceGroupSetting.setPermitLateMinutes(permitLateMinutes);
                    dingTalkAttendanceGroupSetting.setAbsenteeismLateMinutes(absenteeismLateMinutes);
                    dingTalkAttendanceGroupSetting.setIsOffDutyFreeCheck(isOffDutyFreeCheck);
                    dingTalkAttendanceGroupSetting.setClassId(classId);
                    dingTalkAttendanceGroupSetting.setClassName(className);
                    dingTalkAttendanceGroupSetting.setClassSettingId(classSettingId);
                    dingTalkAttendanceGroupSetting.setGroupName(groupName);
                    dingTalkAttendanceGroupSetting.setGroupId(groupId);
                    dingTalkAttendanceGroupSetting.setGroupKeyId(id);


                    DingTalkAttendanceGroupSetting dingTalkAttendanceGroupSetting1 = dingTalkAttendanceGroupSettingDao.selGroupSettingInfo(groupId, classId);
                    if(dingTalkAttendanceGroupSetting1!=null){
                        dingTalkAttendanceGroupSetting.setId(dingTalkAttendanceGroupSetting1.getId());
                        dingTalkAttendanceGroupSettingDao.updateById(dingTalkAttendanceGroupSetting);
                    }else{
                        dingTalkAttendanceGroupSettingDao.insert(dingTalkAttendanceGroupSetting);
                    }


                    // 处理sections
                    JSONArray sectionsArray = selectedClassObject.getJSONArray("sections");
                    for (int k = 0; k < sectionsArray.size(); k++) {
                        JSONObject sectionObject = sectionsArray.getJSONObject(k);
                        JSONArray timesArray = sectionObject.getJSONArray("times");

                        for (int l = 0; l < timesArray.size(); l++) {
                            JSONObject timeObject = timesArray.getJSONObject(l);
                            DingTalkAttendanceGroupSettingTimes dingTalkAttendanceGroupSettingTimes=new DingTalkAttendanceGroupSettingTimes();
                            Integer across = timeObject.getInteger("across");
                            String checkTime = timeObject.getString("check_time");
                            String checkType = timeObject.getString("check_type");


                            dingTalkAttendanceGroupSettingTimes.setAcross(across);
                            dingTalkAttendanceGroupSettingTimes.setCheckTime(checkTime);
                            dingTalkAttendanceGroupSettingTimes.setCheckType(checkType);
                            dingTalkAttendanceGroupSettingTimes.setGroupName(groupName);
                            dingTalkAttendanceGroupSettingTimes.setGroupId(groupId);
                            dingTalkAttendanceGroupSettingTimes.setClassId(classId);
                            dingTalkAttendanceGroupSettingTimes.setClassName(className);
                            dingTalkAttendanceGroupSettingTimes.setGroupKeyId(id);

                            dingTalkAttendanceGroupSettingTimesDao.insert(dingTalkAttendanceGroupSettingTimes);
                        }
                    }
                }
            }

        }catch (Exception e){
            log.info("同步考勤组系统设置的相关时间入系统发生问题",e);
        }



    }



}
